package com.scaupos.mis11c.shirologin.shiro;

import com.scaupos.mis11c.Entities.SystemUsers;
import com.scaupos.mis11c.Repository.SystemUsersRepository;
import com.scaupos.mis11c.shirologin.util.JWTUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.scaupos.mis11c.shirologin.database.UserService;
import com.scaupos.mis11c.shirologin.database.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Service
public class MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);

    //private UserService userService;


    @Autowired
//    public void setUserService(UserService userService) {
//        this.userService = userService;
//    }
    SystemUsersRepository systemUsersRepository;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    //检查当前权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = JWTUtil.getUsername(principals.toString());
        //UserBean user = userService.getUser(username);
        SystemUsers user = systemUsersRepository.findByUsername(username);
        //System.out.println(systemUsersRepository);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(user.getRole());
        Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(",")));
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    //默认验证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();

        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        //UserBean userBean = userService.getUser(username);
        SystemUsers userBean = systemUsersRepository.findByUsername(username);
        if (userBean == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (! JWTUtil.verify(token, username, userBean.getPassword())) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
